package menu.lt.pers.menu.adapter;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.*;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import menu.lt.pers.menu.Bean.RecipeBean;
import menu.lt.pers.menu.Bean.ResultByNameBean;
import menu.lt.pers.menu.Bean.UserBean;
import menu.lt.pers.menu.R;
import menu.lt.pers.menu.RecipeInfo;
import menu.lt.pers.menu.dao.CollectionDao;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class RecipeRecyclerViewAdapter extends RecyclerView.Adapter<RecipeRecyclerViewAdapter.MyHolder>{
    private Context context;
    private List<RecipeBean> list;
    private HashMap<String,Bitmap> bitmapList;
    private List<ResultByNameBean.ResultBean.ListBean.MaterialBean> materials;
    private List<ResultByNameBean.ResultBean.ListBean.ProcessBean> processes;
    private Cursor cursor;
    private CollectionDao dao;
    private UserBean user;
    public RecipeRecyclerViewAdapter(Context context,UserBean user) {
        this.context = context;
        this.bitmapList = new HashMap<>();
        this.dao = new CollectionDao(context);
        this.user = user;
        this.list = new ArrayList<>();
        getData();
    }

    private void getData() {
        cursor = dao.findByUserId(user);
        if(cursor.moveToFirst()){
            list.clear();
            do {
                RecipeBean recipe = new RecipeBean();
                int _id = cursor.getInt(0);
                int class_id = cursor.getInt(1);
                String name = cursor.getString(2);
                String peoplenum = cursor.getString(3);
                String preparetime = cursor.getString(4);
                String cookingtime = cursor.getString(5);
                String content = cursor.getString(6);
                String pic = cursor.getString(7);
                String tag = cursor.getString(8);
                String materialJson = cursor.getString(9);
                String processJSon = cursor.getString(10);
                int user_id = cursor.getInt(11);

                recipe.set_id(_id);
                recipe.setClassid(class_id);
                recipe.setName(name);
                recipe.setPeoplenum(peoplenum);
                recipe.setPreparetime(preparetime);
                recipe.setCookingtime(cookingtime);
                recipe.setContent(content);
                recipe.setPic(pic);
                recipe.setTag(tag);
                recipe.setMaterialJson(materialJson);
                recipe.setProcessJson(processJSon);
                recipe.setUserid(user_id);
                Log.i("Fragment_my.btn_collection.setOnClickListener",recipe.getPic());
                list.add(recipe);
            }while(cursor.moveToNext());
            cursor.close();
            for (int i = 0;i<list.size();i++){
                Log.i("Fragment_my.btn_collection.setOnClickListener",list.get(i).getName());
            }
            Log.i("btn_collection.setOnClickListener", "onClick: "+list.toString());
        }
    }

    public Context getContext() {
        return context;
    }
    public void update(HashMap<String,Bitmap> bitmapList){
        this.bitmapList = bitmapList;
        notifyDataSetChanged();
    }

    public List<RecipeBean> getList() {
        return list;
    }

    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater
                .from(viewGroup.getContext())
                .inflate(R.layout.classactivity_listview_resource,viewGroup,false);
        MyHolder holder = new MyHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull final MyHolder myHolder, int i) {
        new GetBimap().execute(list.get(i).getPic(),list.get(i).getName());
        if (bitmapList.get(list.get(i).getName())!=null){
            myHolder.imageView.setImageBitmap(bitmapList.get(list.get(i).getName()));
        } else {
            myHolder.imageView.setImageResource(R.drawable.timg);
        }
        myHolder.tv_recipename.setText(list.get(i).getName());
        String materialJSON = list.get(i).getMaterialJson();
        final Gson gson = new Gson();

        final int index = i;
        materials = gson.fromJson(materialJSON,
                new TypeToken<ArrayList<ResultByNameBean.ResultBean.ListBean.MaterialBean>>() {}.getType());
        processes = gson.fromJson(list.get(i).getProcessJson(),
                new TypeToken<ArrayList<ResultByNameBean.ResultBean.ListBean.ProcessBean>>() {}.getType());

        Log.i("RecipeRecyclerViewAdapter.onBindViewHolder", "onBindViewHolder: "+processes.size());

        String materialsContent = "";
        for (ResultByNameBean.ResultBean.ListBean.MaterialBean item:materials){
            materialsContent = materialsContent + item.getMname()+",";
        }
        myHolder.tv_recipematerial.setText(materialsContent.substring(0,materialsContent.length()-1));

        myHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ResultByNameBean.ResultBean.ListBean recipe = new ResultByNameBean.ResultBean.ListBean();
                recipe.setMaterial(materials);
                recipe.setProcess(processes);
                recipe.setId(list.get(index).get_id());
                recipe.setClassid(list.get(index).getClassid());
                recipe.setContent(list.get(index).getContent());
                recipe.setCookingtime(list.get(index).getCookingtime());
                recipe.setName(list.get(index).getName());
                recipe.setPeoplenum(list.get(index).getPeoplenum());
                recipe.setPreparetime(list.get(index).getPreparetime());
                recipe.setPic(list.get(index).getPic());
                recipe.setTag(list.get(index).getTag());
                Intent intent = new Intent(context, RecipeInfo.class);
                for (int i = 0 ; i<materials.size();i++){
                    Log.i("materials", "onClick: "+materials.get(i).getMname());
                }
                for (int i = 0 ; i<processes.size();i++){
                    Log.i("processes", "onClick: "+processes.get(i).getPcontent());
                }

                intent.putExtra("recipe",gson.toJson(recipe));
                Log.i("itemView.setOnClickListener", "onClick: "+"准备跳转");
                context.startActivity(intent);
            }
        });
        myHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                PopupMenu popup = new PopupMenu(context, myHolder.itemView);//第二个参数是绑定的那个view
                MenuInflater inflater = popup.getMenuInflater();
                inflater.inflate(R.menu.collection_menu, popup.getMenu());
                popup.show();
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()){
                            case R.id.del_menu: //删除
                                dao.delete(list.get(index).get_id());
                                list.remove(index);
                                notifyDataSetChanged();
                                break;
                        }
                        return true;
                    }
                });
                return true;
            }
        });

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class MyHolder extends RecyclerView.ViewHolder {
        TextView tv_recipename;
        TextView tv_recipematerial;
        ImageView imageView;
        public MyHolder(@NonNull View itemView) {
            super(itemView);
            tv_recipename = itemView.findViewById(R.id.tv_recipename);
            tv_recipematerial = itemView.findViewById(R.id.tv_recipematerial);
            imageView = itemView.findViewById(R.id.imageView);
        }
    }
    class GetBimap extends AsyncTask {
        private String key;
        @Override
        protected Bitmap doInBackground(Object[] params) {
            key = (String) params[1];
            if (bitmapList.get(key)==null){
                String uripath = (String) params[0];
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(5000, TimeUnit.SECONDS)
                        .readTimeout(5000,TimeUnit.SECONDS)
                        .build();
                Request request = new Request.Builder()
                        .url(uripath)
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()){
                        InputStream inputStream = response.body().byteStream();//得到图片的流
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        return bitmap;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (o!=null){
                Bitmap bitmap = (Bitmap) o;
                bitmapList.put(key,bitmap);
                    bitmapList.put(key,bitmap);
                    update(bitmapList);
                }
            }
        }

}
